import React, { useState, useRef, useEffect } from 'react';
import { motion, useInView } from 'framer-motion';
import { useThemeStore } from '../../stores/themeStore';
import { getTheme } from '../../theme/config';
import '../custom/customComponents.css';

interface AnimatedListItem {
  id: string | number;
  content: React.ReactNode;
  [key: string]: any;
}

interface AnimatedListProps {
  items: AnimatedListItem[];
  onSelect?: (item: AnimatedListItem) => void;
  selectedItem?: string | number;
  showGradients?: boolean;
  hideScrollbar?: boolean;
  containerWidth?: number | string;
  maxHeight?: number;
  className?: string;
}

interface AnimatedItemProps {
  children: React.ReactNode;
  index: number;
  onMouseEnter?: React.MouseEventHandler<HTMLDivElement>;
  onClick?: React.MouseEventHandler<HTMLDivElement>;
}

const AnimatedItem: React.FC<AnimatedItemProps> = ({ children, index, onMouseEnter, onClick }) => {
  const ref = useRef<HTMLDivElement>(null);
  const inView = useInView(ref, { amount: 0.1, once: true });
  
  return (
    <motion.div
      ref={ref}
      data-index={index}
      onMouseEnter={onMouseEnter}
      onClick={onClick}
      initial={{ scale: 0.7, opacity: 0 }}
      animate={inView ? { scale: 1, opacity: 1 } : { scale: 0.7, opacity: 0 }}
      transition={{ duration: 0.3 }}
      className="animated-list-item"
    >
      {children}
    </motion.div>
  );
};

const AnimatedList: React.FC<AnimatedListProps> = ({
  items = [],
  onSelect,
  selectedItem,
  showGradients = true,
  hideScrollbar = false,
  containerWidth = 500,
  maxHeight = 400,
  className = '',
}) => {
  const { mode } = useThemeStore();
  const theme = getTheme(mode);
  const [showTopGradient, setShowTopGradient] = useState(false);
  const [showBottomGradient, setShowBottomGradient] = useState(false);
  const scrollContainerRef = useRef<HTMLDivElement>(null);

  const handleScroll = () => {
    if (!scrollContainerRef.current || !showGradients) return;
    
    const { scrollTop, scrollHeight, clientHeight } = scrollContainerRef.current;
    setShowTopGradient(scrollTop > 0);
    setShowBottomGradient(scrollTop < scrollHeight - clientHeight - 1);
  };

  useEffect(() => {
    handleScroll();
  }, [items, showGradients, mode]);

  const handleItemClick = (item: AnimatedListItem) => {
    if (onSelect) {
      onSelect(item);
    }
  };

  // 根据主题模式设置阴影效果
  const getBoxShadow = () => {
    if (mode === 'light') {
      return '0 4px 12px rgba(0, 0, 0, 0.05)';
    }
    return theme.cardShadow;
  };

  return (
    <div 
      className={`animated-list-container ${className}`}
      style={{ width: containerWidth }}
    >
      <div
        ref={scrollContainerRef}
        className={`
          animated-list-scroll
          ${hideScrollbar ? 'hide-scrollbar' : ''}
        `}
        style={{ 
          maxHeight: `${maxHeight}px`,
          padding: '16px',
          borderRadius: '16px'
        }}
        onScroll={handleScroll}
      >
        {items.map((item, index) => (
          <AnimatedItem
            key={item.id}
            index={index}
            onMouseEnter={() => {}}
            onClick={() => handleItemClick(item)}
          >
            <div
              className="animated-list-item-content"
              style={{
                backgroundColor: selectedItem === item.id 
                  ? theme.listSelectedItemBackground 
                  : theme.listBackground,
                border: `1px solid ${selectedItem === item.id ? theme.glowColor : theme.listBorder}`,
                boxShadow: getBoxShadow(),
                backdropFilter: mode === 'dark' ? 'blur(20px)' : 'blur(10px)',
                WebkitBackdropFilter: mode === 'dark' ? 'blur(20px)' : 'blur(10px)',
                transform: selectedItem === item.id ? 'translateY(-2px)' : 'none',
                borderRadius: '16px',
                marginBottom: '16px',
                padding: '24px',
                transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
                position: 'relative',
                overflow: 'hidden'
              }}
              onMouseEnter={(e) => {
                // 统一悬停效果，不论主题
                e.currentTarget.style.boxShadow = mode === 'dark' 
                  ? '0 8px 24px rgba(0, 0, 0, 0.3)' 
                  : '0 8px 24px rgba(0, 0, 0, 0.12)';
                e.currentTarget.style.transform = 'translateY(-4px)';
                
                // 添加悬停时的背景效果
                if (selectedItem !== item.id) {
                  e.currentTarget.style.backgroundColor = theme.listHoverBackground;
                }
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.boxShadow = getBoxShadow();
                e.currentTarget.style.transform = selectedItem === item.id ? 'translateY(-2px)' : 'none';
                
                // 恢复背景色
                if (selectedItem !== item.id) {
                  e.currentTarget.style.backgroundColor = theme.listBackground;
                }
              }}
            >
              {/* 添加选中状态的装饰效果 */}
              {selectedItem === item.id && (
                <div style={{
                  position: 'absolute',
                  top: 0,
                  left: 0,
                  right: 0,
                  height: '2px',
                  background: `linear-gradient(90deg, ${theme.glowColor}, transparent)`
                }} />
              )}
              
              {/* 添加悬停时的微光效果 */}
              <div 
                style={{
                  position: 'absolute',
                  top: 0,
                  left: '-100%',
                  width: '100%',
                  height: '100%',
                  background: `linear-gradient(90deg, transparent, ${mode === 'dark' ? 'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.05)'}, transparent)`
                }}
                className="list-item-shimmer"
              />
              
              <div style={{ 
                color: theme.textPrimary,
                position: 'relative',
                zIndex: 1
              }}>
                {item.content}
              </div>
            </div>
          </AnimatedItem>
        ))}
      </div>

      {showGradients && (
        <>
          <div 
            className="animated-list-gradient-top"
            style={{ 
              background: `linear-gradient(to bottom, ${theme.contentBackground}, transparent)`,
              opacity: showTopGradient ? 1 : 0 
            }}
          />
          <div 
            className="animated-list-gradient-bottom"
            style={{ 
              background: `linear-gradient(to top, ${theme.contentBackground}, transparent)`,
              opacity: showBottomGradient ? 1 : 0 
            }}
          />
        </>
      )}
    </div>
  );
};

export default AnimatedList;